package com.soulapp.hook.hooker

import android.content.Context
import android.view.LayoutInflater
import android.widget.Toast
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.google.android.material.slider.LabelFormatter
import com.highcapable.kavaref.KavaRef.Companion.resolve
import com.highcapable.kavaref.condition.type.Modifiers
import com.highcapable.kavaref.condition.type.VagueType
import com.highcapable.yukihookapi.hook.core.YukiMemberHookCreator.MemberHookCreator.Result
import com.highcapable.yukihookapi.hook.factory.applyModuleTheme
import com.highcapable.yukihookapi.hook.log.YLog
import com.soulapp.data.ConfigData
import com.soulapp.hook.databinding.DialogInputAgeBinding

// 修改瞬间匹配年龄
object MomentAgeHook : BaseHooker() {
    private const val TAG = "MomentAgeHook"
    private var hook: Result? = null
    override fun getKey() = ConfigData.momentAge

    // cn.soulapp.android.component.planet.planet.api.IPlanetApi
    override fun onHook() {
        startHook()
    }

    override fun startHook() {
        YLog.debug("startHook $TAG $hookEnabled")
        if (!hookEnabled) return

        hook = "xn.b".toClass()
            .resolve()
            .optional()
            .method {
                modifiers(Modifiers.PUBLIC, Modifiers.STATIC)
                name("f")
                parameters(VagueType, VagueType)
                returnType = Void::class.javaPrimitiveType
            }.first()
            .hook {
                before {
                    val originalMap = args[0] as? Map<*, *> ?: return@before
                    // 创建可变副本
                    val mutableMap = HashMap(originalMap)

                    // 修改副本内容
                    val minAge = ConfigData.getInt(ConfigData.momentMinAge)
                    val maxAge = ConfigData.getInt(ConfigData.momentMaxAge)
                    mutableMap["minAge"] = minAge
                    mutableMap["maxAge"] = maxAge

                    val showToast = ConfigData.getBoolean(ConfigData.showToast)
                    if (showToast) {
                        Toast.makeText(appContext, "匹配年龄：${minAge}-${maxAge}", Toast.LENGTH_SHORT).show()
                    }
                    YLog.debug("hook $TAG 搜索年龄：${minAge}-${maxAge}")
                    // 替换原始参数
                    args[0] = mutableMap
                }
            }
        // testHook(className)
    }

    fun showAgeDialog(context: Context) {
        // ✅ 使用 applyModuleTheme 包装 context，注入 AppCompat 主题
        val themedContext = context.applyModuleTheme(com.soulapp.hook.R.style.AppTheme)
        val binding = DialogInputAgeBinding.inflate(LayoutInflater.from(themedContext))
        val dialogView = binding.root
        val ageRangeSlider = binding.ageRangeSlider
        // 设置初始值
        val momentMinAge = ConfigData.getInt(ConfigData.momentMinAge, 18)
        val momentMaxAge = ConfigData.getInt(ConfigData.momentMaxAge, 50)
        ageRangeSlider.values = listOf(momentMinAge.toFloat(), momentMaxAge.toFloat())
        // 设置标签始终可见
        ageRangeSlider.labelBehavior = LabelFormatter.LABEL_VISIBLE

        // 构建对话框
        MaterialAlertDialogBuilder(themedContext)
            .setTitle("选择年龄")
            .setView(dialogView)
            .setPositiveButton("确定") { dialog, _ ->
                val values = ageRangeSlider.values
                if (values.size >= 2) {
                    val minAge = values[0].toInt()
                    val maxAge = values[1].toInt()
                    ConfigData.putInt(ConfigData.momentMinAge, minAge)
                    ConfigData.putInt(ConfigData.momentMaxAge, maxAge)
                    Toast.makeText(context, "匹配年龄：${minAge}-${maxAge}", Toast.LENGTH_SHORT).show()
                }

                dialog.dismiss()
            }
            .setNegativeButton("取消") { dialog, _ ->
                dialog.dismiss()
            }
            .show()
    }

    // 重写clickListener属性并赋值
    override var clickListener: ((context: Context) -> Unit)? = { context ->
        showAgeDialog(context)
    }

    override fun stopHook() {
        if (hookEnabled) return

        hook?.let {
            it.remove {
                YLog.debug("stopHook $TAG 成功")
            }
        } ?: YLog.debug("stopHook $TAG 失败")

    }
}